<template>
<div>

    <div style="margin: 10px 0">
      <el-input style="width: 200px" placeholder="请输入用户" suffix-icon="el-icon-search" v-model="appid"></el-input>
      <el-select v-model="orderStatus" placeholder="请选择订单状态">
        <el-option label="已消费" value="1"></el-option>
        <el-option label="未消费" value="0"></el-option>
      </el-select>
      <el-input style="width: 200px" placeholder="请输入取单号" suffix-icon="el-icon-position" class="ml-5"
                v-model="orderNum"></el-input>
      <el-input style="width: 200px" placeholder="请输入订单号" suffix-icon="el-icon-position" class="ml-5"
                v-model="oddNum"></el-input>
      <el-button class="ml-5" type="primary" @click="getList">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
    </div>

  <div style="margin: 10px 0">
    <el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
    <el-popconfirm
        class="ml-5"
        confirm-button-text='确定'
        cancel-button-text='我再想想'
        icon="el-icon-info"
        icon-color="red"
        title="您确定批量删除这些数据吗？"
        @confirm="delBatch"
    >
      <el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button>
    </el-popconfirm>
    <el-button type="primary" @click="exportOrders">导出 <i class="el-icon-top"></i></el-button>
  </div>
  <el-dialog
      :title="title"
      :visible.sync="openDetail"
      width="55%"
      append-to-body
      style="height: 700px"
  >
    <el-table :data="detailInfo" border style="width: 100%">
      <el-table-column prop="id" align="center" label="菜品id" />
      <el-table-column prop="dishName" align="center" label="菜品名字" />
      <!-- <el-table-column prop="name" label="菜品图片" /> -->
      <el-table-column prop="dishCount" align="center" label="菜品数量" />
      <el-table-column
          prop="introduce"
          align="center"
          label="菜品描述"
          width="400"
      />
      <el-table-column prop="type" label="菜品类型" />
    </el-table>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="cancelDetail">确 定</el-button>
    </div>
  </el-dialog>


  <el-table
      border
      :data="ordersList"
      @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55" align="center" />
    <el-table-column label="用户" align="center" prop="appid" />
    <el-table-column label="取单号" align="center" prop="orderNum" />
    <el-table-column label="订单编号" align="center" prop="oddNum" />
    <el-table-column label="已消费" align="center" prop="status">
      <!-- scope 就是后端传来的ordersList -->
      <template slot-scope="scope">
        <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @click.native="switchStatus(scope.row, $event)"
        >
          <!-- $event 开关变化后的值 scope.row.id后端传来的order_id -->
        </el-switch>
      </template>
    </el-table-column>
    <el-table-column label="通知取餐" align="center" prop="mealStatus">
      <!-- scope 就是后端传来的ordersList -->
      <template slot-scope="scope">
        <el-switch
            v-model="scope.row.mealStatus"
            :active-value="1"
            :inactive-value="0"
            @click.native="switchMealStatus(scope.row, $event)"
        >
          <!-- $event 开关变化后的值 scope.row.id后端传来的order_id -->
        </el-switch>
      </template>
    </el-table-column>
    <el-table-column label="总价" align="center" prop="priceAll" />
    <el-table-column prop="shopName" align="center" label="所属店铺" />
    <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
    >
      <template slot-scope="scope">
        <el-button
            size="mini"
            type="text"
            icon="el-icon-s-order"
            @click="seeOrderDetail(scope.row)"
        >订单详情</el-button
        >
        <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
        >修改</el-button
        >
        <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
        >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>
  <div style="padding: 10px 0">
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-sizes="[5, 10, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
  </div>
  <el-dialog :title="title" :visible.sync="open" width="74%" append-to-body>
    <el-form
        ref="form"
        :inline="true"
        :model="orderFrom"
        :rules="rules"
        label-width="70px"
    >
      <el-row>
        <el-col>
          <el-form-item label="店铺名" prop="shopId">
            <el-select
                @change="onchangShopId"
                @visible-change="selectShop"
                v-model="orderFrom.shopId"
                :disabled="editShop"
                placeholder="请选择店铺名"
            >
              <el-option
                  v-for="shop in shops"
                  :key="shop.id"
                  :label="shop.name"
                  :value="shop.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="用户" prop="appid">
            <el-input
                :disabled="editShop"
                v-model="orderFrom.appid"
                placeholder="请输入用户"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col v-for="(dish, index) in orderFrom.orderDishVo" :key="dish.id">
          <el-form-item
              label="菜品名字"
              :prop="'orderDishVo[' + index + '].dishName'"
          >
            <el-select
                @change="onchangDishName($event, index)"
                :disabled="disabled"
                v-model="dish.dishId"
                placeholder="请选择菜品"
            >
              <el-option
                  v-for="item in dishName"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
              <!-- 原生的点击事件@click.native="deleteDishName(i)" -->
            </el-select>
          </el-form-item>
          <el-form-item
              label="菜品数量"
              :prop="'orderDishVo[' + index + '].dishCount'"
          >
            <el-input
                :disabled="disabled"
                v-model="dish.dishCount"
                placeholder="请输入菜品数量"
            />
          </el-form-item>
          <el-form-item
              label="菜品描述"
              :prop="'orderDishVo[' + index + '].introduce'"
          >
            <el-input
                :disabled="disabled"
                v-model="dish.introduce"
                placeholder="请描述菜品"
            />
          </el-form-item>
          <el-button
              size="mini"
              type="danger"
              plain
              icon="el-icon-delete"
              @click="deleteDishNode(index)"
              v-hasPermi="['system:orders:remove']"
          >删除</el-button
          >
          <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="addDishNode(index)"
              v-hasPermi="['system:orders:add']"
          >新增</el-button
          >
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</div>
</template>

<script>
export default {
  name: "AdminOrder",
  data(){
    return{
      detailInfo: [],
      openDetail: false,
      ids:[],
      appid:null,
      orderNum:null,
      oddNum:null,
      orderStatus:null,
      ordersList:[],
      multipleSelection: [],
      total: 0,
      currentPage: 1,
      pageSize: 5,
      title:"",
      orderFrom:{},
      dishName: [],
      shops:[],
      //是否可以选择店铺
      editShop: false,
      //组件是否禁用
      disabled: true,
      rules: {
        appid: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 1,
            max: 30,
            message: "长度在 1 到 30 个字符",
            trigger: "blur",
          },
        ],
        shopId: [{ required: true, message: "请选择店铺", trigger: "blur" }],
      },
      open:false
    }
  },
  created() {
    this.getList()
  },
  methods:{
    cancelDetail() {
      this.openDetail = false;
    },
    submitForm(){
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.orderFrom.id != null) {
           // 修改
            this.request.put("/admin/updateOrder",this.orderFrom).then(res=>{
              if (res.code===200){
                this.$message.success("修改成功")

                this.open=false
                this.editShop = false;
                this.getList()
              }else {
                this.$message.error("删除失败")

              }
            })
          } else {
            //添加
            this.request.post("/customer/addOrder",this.orderFrom).then(res=>{
              if (res.code === 200) {
                this.$message.success("添加成功")

                this.open = false;
                this.editShop = false;
                this.getList();
              }else {
                this.$message.error("删除失败")

              }
            })
          }
        }
      });
    },
    cancel(){
      this.open=false
      this.editShop = false;
      this.reset();
    },
    //添加菜品节点
    addDishNode(index) {
      if (this.orderFrom.shopId == null) {
        this.$message.warning("选择完店铺才可以添加菜品哦！");
        return;
      }
      if (this.dishName.length == 0 && this.shops.name != null) {
        this.$message.warning("此店铺没有菜品可添加！");
        return;
      }
      //菜品信息如果都填了如果都不为空就禁用
      if (
          this.orderFrom.orderDishVo[index].dishId == null ||
          this.orderFrom.orderDishVo[index].dishCount == null ||
          this.orderFrom.orderDishVo[index].introduce == null
      ) {
        this.$message({
          message: "菜品信息请填写完全！",
          duration: 3000,
          type: "warning",
        });
        return;
      }
      if (this.orderFrom.orderDishVo.length < this.dishName.length) {
        this.orderFrom.orderDishVo.push({
          dishId: null,
          dishName: null,
          dishCount: null,
          introduce: null,
        });
      } else {
        this.$message.warning("此店铺仅有" + this.dishName.length + "种菜品");
      }
    },
    //删除结点
    deleteDishNode(index) {
      //判断数组长度至少保留1
      if (this.orderFrom.orderDishVo.length > 1) {
        this.orderFrom.orderDishVo.splice(index, 1);
      } else {
        this.$message.warning("菜品至少要保留一个！");
      }
    },
    onchangDishName(dishId, index) {
      //回调还可以这么玩，开关那个是另一种玩法
      //从第二个开始遍历检查是否菜品选的重复
      for (let i = 1; i <= index; i++) {
        let dish = this.orderFrom.orderDishVo[i - 1].dishId;
        if (dishId == dish) {
          this.$message.warning("你已选过此菜,请重新选择");
          this.orderFrom.orderDishVo[i].dishId = null;
        }
      }
    },
    //店铺选择框一打开就查询店铺名字
    selectShop(value) {
      if (value) {
      }
    },
    //选中值发生变化时触发
    onchangShopId(shopId){
      //查询店铺下的所有菜品
      this.request.get("/getDishOptions/"+shopId).then(res=>{
        this.dishName=res.data
        if (this.dishName == null || this.dishName.length == 0) {
          this.$message.warning("此店铺没有菜品或没有此店铺");
          this.disabled = true;
          return;
        }
        this.disabled = false;
      })
    },
    getList(){
        this.request.get("/admin/orderList",{
          params: {
            currentPage: this.currentPage,
            pageSize: this.pageSize,
            appid:this.appid,
            orderNum:this.orderNum,
            oddNum:this.oddNum,
            orderStatus:this.orderStatus,
          }
        }).then(res=>{
          this.currentPage = res.data.current
          this.pageSize = res.data.size
          this.total = res.data.total
          this.ordersList = res.data.records
        })
    },
    switchStatus(row, e){
      //阻止默认事件
      e.stopPropagation();
      //发送请求
      this.request.put("/admin/updateStatus",{
         id: row.id, status: row.status
      }).then(res=>{
        if (res.code===200){
          this.$message.success("修改状态成功")

        }else{
          this.$message.error("修改状态失败")

        }
      })
    },
    switchMealStatus(row, e){
      //阻止默认事件
      e.stopPropagation();
      //发送请求
      this.request.put("/admin/updateMealStatus",{
        id: row.id, mealStatus: row.mealStatus
      }).then(res=>{
        if (res.code===200){
          this.$message.success("修改状态成功")

        }else{
          this.$message.error(res.msg)
          this.getList()
        }
      })
    },
    seeOrderDetail(row){
      this.detailInfo = row.orderDishVo;
      this.openDetail = true;
      this.title = "订单详情";
    },
    handleAdd(){
      this.reset();
      this.shops = [];
      this.open = true;
      this.editShop = false;
      this.title = "添加订单";
    },
    handleUpdate(row){
      const id=row.id
      this.request.get("/admin/orderForm/"+id).then(res=>{
        this.orderFrom = res.data;
        this.open = true;
        this.title = "修改订单";
        this.editShop = true;
        this.disabled = false;
      })
    },
    delBatch(){

        this.request.delete("/admin/deleteOrder/"+this.ids).then(res => {
          if (res.code===200) {
            this.$message.success("删除成功")
            this.getList()
          } else {
            this.$message.error("删除失败")
          }
        })
    },
    handleDelete(row){
      this.ids=[]
      this.ids.push(row.id)
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request.delete("/admin/deleteOrder/"+this.ids).then(res => {
          if (res.code===200) {
            this.$message.success("删除成功")
            this.getList()
          } else {
            this.$message.error("删除失败")
          }
        })
      }).catch(() => {
        //用户点击取消按钮
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleSelectionChange(val){
      this.ids = val.map((item) => item.id);
    },
    handleSizeChange(val) {
      //每页多少条
      this.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      //当前第几页
      this.currentPage = val
      this.getList()
    },
    exportOrders(){
      window.open(`http://localhost:9090/hbgc/admin/ordersExport`)
    },

    reset() {
      this.orderFrom = {
        //用户id
        appid: null,
        //店铺id
        shopId: null,
        //菜品数组
        orderDishVo: [
          { dishId: null, dishName: null, dishCount: null, introduce: null },
        ],
      };
      this.appid=null,
          this.orderNum=null,
          this.oddNum=null,
          this.orderStatus=null,
      this.dishName = [];
      this.disabled = true;
    },
  },
  watch: {
    //如果添加或修改的弹出层打开了，就查询店铺的名字
    open: {
      handler(newValue) {
        if (newValue) {
          //查询店铺的名字
          this.request.get("/selectOptions").then((res) => {
            this.shops = res.data;
          });
        }
      },
    },
  },
}
</script>

<style scoped>

</style>